﻿
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>D站</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link rel="icon" th:href="@{/pagesResource/img/icon.png}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/animate.css}">
<!--    <link type="text/css" rel="stylesheet" th:href="@{/pagesResource/css/CustomerIndex.css}"/>-->
    <!--    <link type="text/css" rel="stylesheet" th:href="@{/pagesResource/css/global.css}"/>-->
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/bootstrap.min.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/iconfont.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/style.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/responsive.css}">
    <link rel="stylesheet" type="text/css" th:href="@{/pagesResource/css/color.css}">
    <script th:src="@{/js/sweetAlert.js}"></script>
</head>

<body>
<div class="wrapper hp_1">
    <!-- 引入头部 -->
    <div th:include="main/simpleHeader :: header"></div>

</div>
<!-- 总容器 container开 始-->
<section class="vds-main">
    <div class="container" style="max-width: 1170px;">
        <div class="dyn-main">
            <div class="dyn-main-banner">
                <div class="main-banner-top">
                    <!--发布框-->
                    <div class="main-banner-issue">
                        <!--id=mainBannerTopIssuePoint 提示-->
                        <div id="top-issue-point">分享你的所感所想吧
                        </div>
                        <div style="float:right;">还可以输入<span id="counter1">500</span>字！
                        </div>
                        <form action="" method="post" id="dynamicForm" role="form">
                            <div class="top-issue-form">
                                <!--发布动态框-->
                                <div class="top-issue-frame">
                                    <textarea name="textfield1" rows="4" class="Size" id="textfield2"
                                              style="overflow:hidden;border:1px #0CF solid;" maxlength="500"
                                              onkeyup="calNum(this,counter1,0)"></textarea>
                                </div>
                                <!--发布动态框下按钮组-->
                                <div class="top-issue-buttons">
                                    <div class="top-issue-buttons-left">
                                        <!--图片上传-->
                                        <span class="iconfont icon-img" id="dynImgUpload"></span>
                                        <input name="file" id="topIssueImages" type="file" accept="image/*"
                                               multiple="multiple" style="display:none">
                                    </div>
                                    <input type="button" name="button1" id="publishDynamic" value="发布"
                                           onclick="submitState()"/>
                                </div>
                                <div class="top-issue-images"></div>
                            </div>
                        </form>
                    </div>
                </div>

                <!--id="mainBannerTitle 首页-->
                <div class="main-banner-title">
                    <!--id="mainBannerTitleWord"-->
                    <div class="title-word"><b>首页</b>
                    </div>
                </div>
                <!--不同人的内容-->
                <div class="main-banner-content">
                    <!--个人展示-->
                    <div class="stateShow"
                         th:each="dynamic:${dynamicList}">
                        <div class="stateShowWord">
                            <table width="450" border="0" cellpadding="0" cellspacing="0" class="stateTable">
                                <tr>
                                    <td width="80" align="center" valign="top">
                                        <a th:href="@{/user/userMainPage}+ '?userId='+${dynamic.userId}">
                                        <img
                                            th:src="@{/images/userIcon/{creatorIcon}(creatorIcon=${dynamic.creatorIcon})}"
                                            th:alt="${dynamic.creatorIcon}" width="48" style="border-radius: 10px;"
                                            height="48"/><span th:text="${dynamic.creatorName}">乡下妹</span>
                                        </a>
                                    </td>
                                    <td width="440" th:id="${dynamic.dynamicId}">
                                        <th:block th:if="${session.userInfo.userId==dynamic.userId}">
                                            <a th:href="@{/dynamic/updateDynamicInfoPage}+ '?dynamicId='+${dynamic.dynamicId}">
                                                <span class="iconfont icon-bianji"></span>
                                            </a>
                                        </th:block>
                                        <a th:href="@{/dynamic/findDynamicInfo}+ '?dynamicId='+${dynamic.dynamicId}">
                                            <p th:text="${dynamic.dynamicContent}">
                                                【视频：超模的儿子每月需要30万元生活费？】-
                                                超模琳达·伊万格丽斯塔为四岁的儿子向他的父亲、法国亿万富翁弗朗索瓦-亨利·皮诺特索要每月4.6万美元的抚养费。在视频中，《华尔街日报》的Robert
                                                Frank和Kelsey Hubbard讨论了富豪家庭在孩子身上的花销。
                                            </p>
                                        </a>
                                        <div class="stateImgShow">
                                            <div class="ImgShowDiv" th:each="image:${dynamic.images}" >
                                                <a class="thumbnail" th:href="@{/images/dynImages/{image}(image=${image})}" th:rel="${dynamic.dynamicId}" target="_blank">
                                                    <img th:src="@{/images/dynImages/{image}(image=${image})}" th:alt="${image}">
                                                </a>
                                            </div>
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                        <div class="stateShowtime" th:text="${dynamic.createDate}" style="text-align:end"> 07月31日 08:02</div>
                        <div class="stateOp">
                            <a class="opState" th:onclick="'praise(this,' + ${dynamic.dynamicId} +')'">
                                <span th:if="${dynamic.isPraise} == 1"
                                      class="iconfont icon-dianzan alive"></span>
                                <span th:if="${dynamic.isPraise} == 0"
                                      class="iconfont icon-dianzan "></span>
                                <span class="praiseNum" th:text="${dynamic.likedNum}"></span>
                            </a>
                            <th:block th:if="${session.userInfo.userId==dynamic.userId}">
                                <a class="opState" th:onclick="'delState(this,\''+${dynamic.dynamicId}+'\')'"><span class="iconfont icon-shanchu"></span></a>
                            </th:block>
                        </div>
                        <div class="huifu"></div>
                    </div>
                    <!--个人展示结束-->
                </div>
            </div>

        </div>
    </div>
</section>
<script th:src="@{/pagesResource/js/jquery.min.js}"></script>
<script th:src="@{/pagesResource/js/bootstrap.min.js}"></script>
<!--<script th:src="@{/pagesResource/js/CustomerIndex.js}"></script>-->
<script th:src="@{/pagesResource/js/trim.js}"></script>
<script th:src="@{/pagesResource/js/script.js}"></script>
<script>
    Array.prototype.indexOf = function (val) {
        for (var i = 0; i < this.length; i++) {
            if (this[i] == val) return i;
        }
        return -1;
    };
    Array.prototype.remove = function (val) {
        var index = this.indexOf(val);
        if (index > -1) {
            this.splice(index, 1);
        }
    };
    var uploadImg = [];
    $(document).on("click", "#dynImgUpload", function () {
        // 点击图片的同时，点击上传文件的input
        $('#topIssueImages').click();
        $('.top-issue-images').show();
        $('.main-banner-top').css("height", "360px");
    });
    // 将上传的图片显示到页面上
    $(document).on("change", "#topIssueImages", function () {
        var fileDom = document.getElementById("topIssueImages");
        //获取选择的图片文件
        var fileList = fileDom.files;
        for (var i = 0; i < fileList.length; i++) {
            if (uploadImg.length > 3) {
                swal("警告", "只能上传4张图片", "warning");
                break;
            }
            if (checkFile(fileList[i])) {
                uploadImg.push(fileList[i]);
                readFile(fileList[i]);
            }
        }
        console.log(uploadImg);
        var file = $('#topIssueImages');
        file.after(file.clone().val(""));
        file.remove();
    });

    function checkFile(file) {
        //取得上传文件的类型file.files[0].type
        var fileType = file.type.split("/")[0]; //
        //取得上传文件的后缀名
        var fileExt = file.name.split(".")[1];
        //取得上传文件的大小
        var fileSize = file.size;
        //允许上传类型正则
        var pattern = /^(jpg|png|gif|JPG|PNG|GIF)$/;
        //文件大小判断
        if (parseInt(fileSize) > (5 * 1024 * 1024)) {
            swal("错误", "文件大小不能超过5MB！", "error");
            return false;
        }
        //是否是图片
        if (!(fileType == "image")) {
            swal("错误1", "只允许上传这些格式的图片(jpg|png|gif|JPG|PNG|GIF)", "error");
            return false;
        }
        //进行后缀名匹配
        if (!pattern.test(fileExt)) {
            //设置提醒错误内容
            swal("错误2", "只允许上传这些格式的图片(jpg|png|gif|JPG|PNG|GIF)", "error");
            //将组件设置为空
            return false;
        }
        //匹配成功，上传预览
        if (!file) {
            swal("错误", "浏览器不支持文件上传，请升级浏览器版本或者更换浏览器！", "error");
            return false;
        }
        return true;
    }

    function readFile(file) {
        //判断是否支持FileReader
        if (window.FileReader) {
            var reader = new FileReader();
        } else {
            alert("您的浏览器不支持图片预览功能，如需该功能请升级您的浏览器！");
        }
        //获取图片dom
        var $div = $('<div class="dyn-img"></div>');
        var $img = $('<img>');
        var $deleteButton = $('<button type="button" class="dyn-img-btn">X</button>');
        // $deleteButton.attr("onclick","deleteImg("+file.name+")");
        $deleteButton.bind("click", function (e) {
            var $btn = $(e.target);
            var $divimg = $btn.parent();
            var $img = $divimg.children('img');
            var imgname = $img.attr("alt");
            for (var i = 0; i < uploadImg.length; i++) {
                if (imgname == uploadImg[i].name) {
                    uploadImg.remove(uploadImg[i]);
                    break;
                }
            }
            console.log(uploadImg);
            $divimg.remove();
            if (uploadImg.length == 0) {
                $('.top-issue-images').hide();
                $('.main-banner-top').css("height", "217px");
            }
        });
        reader.readAsDataURL(file);
        reader.onload = function (e) {
            //图片路径设置为读取的图片
            $img.attr('src', e.target.result);
        };
        $img.attr('alt', file.name);
        $div.append($img);
        $div.append($deleteButton);
        $('.top-issue-images').append($div);
    }

    /* 动态的计算文本框里面已经输入的数量  */
    function calNum(txtobj, divobj, fg) {
        var str = txtobj.value;
        var n = 500;//初始化数字
        var tmp = str.replace(/[^\w\s]/g, "");//将文本框里面的字符中的中文全部替换成空的
        if (tmp != null)
            n = n - (str.length - tmp.length) - Math.floor(0.5 * tmp.length);//计算，一个中文是1个字符，2个英文是1个
        else
            n = n - Math.floor(0.5 * str.length);//计算，一个中文是1个字符，2个英文是1个
        if (n < 0) {
            swal("错误","你输入的字符数已超出！","error");
            $('#textfield2').css("border","1px #f00 solid;");
        } else {
            if (fg == 1){
                $('#textfield2').css("border","1px #0CF solid;");
            }else{
                $('#textfield2').css("border","1px #000 solid;");
            }
        }
        /* 将计算好的数存入div中 */
        divobj.innerHTML = n;
    }
    /* 当点提交按钮时，对文本框里面的内容进行处理，并进行提交 */
    function submitState() {
        var txtObj = document.getElementById("textfield2");
        txtObj.value = trim(txtObj.value);
        if((uploadImg.length == 0) && (txtObj.value.length == 0)){
            return false;
        }
        if (txtObj.value.length > 0) {
            if (txtObj.value.length > 500){
                swal("错误","你输入的字符数已超出！","error");
                return false;
            }
            // var str = changetxt(txtObj.value);//替换文本框中的表情
            var formData = new FormData();
            formData.append("test", JSON.stringify({'dynamicContent': txtObj.value}));
            if (uploadImg.length == 0){
                $.ajax({
                    url: '/dynamic/saveDynamicInfoOnlyContent',
                    type: "post",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if (data["res"] == "success"){
                            swal("发布动态成功!", {
                                buttons: false,
                                timer: 2000
                            });
                            setTimeout(function () {
                                window.location.reload();
                            }, 1000);
                        }else if (data["res"] == "error"){
                            swal("错误", "发布动态！", "error");
                        }
                    },
                    error: function (data) {
                        swal("错误", "网络错误，请联系管理员！", "error");
                    }
                });
                return;
            }else{
                for (var f of uploadImg) {
                    formData.append("meFile", f);
                }
                $.ajax({
                    url: '/dynamic/saveDynamicInfo',
                    type: "post",
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (data) {
                        if (data["res"] == "success"){
                            swal("发布动态成功!", {
                                buttons: false,
                                timer: 2000
                            });
                            setTimeout(function () {
                                window.location.reload();
                            }, 1000);
                        }else if (data["res"] == "error"){
                            swal("错误", "发布动态失败！", "error");
                        }
                    },
                    error: function (data) {
                        swal("错误", "网络错误，请联系管理员！", "error");
                    }
                });
            }
        }else{
            swal("警告", "需要配上文字描述才能发布哦", "warning");
        }
        txtObj.value = "";//清空文本框
    }
    /* 删除动态 */
    function delState(divObj,dynamicId){
        divObj = divObj.parentNode.parentNode;
        swal({
            title: "删除动态",
            text: "你确定要删除该动态吗？",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        }).then((willDelete) => {
                if (willDelete) {
                    $.ajax({
                        url: '/dynamic/removeDynamicInfo',
                        type: "POST",
                        async: false,    //异步请求
                        cache: true,
                        data: {
                            dynamicId:dynamicId
                        },
                        success: function (data) {
                            if(data["removeRes"]=="success"){
                                swal("删除动态成功!", {
                                    icon: "success",
                                });
                                divObj.parentNode.removeChild(divObj);
                            }else{
                                swal("Error", "删除动态失败！", "error");
                            }
                        },
                        error: function (data) {
                            swal("Error", "网络错误，请联系管理员！", "error");
                        }
                    })

                }
        });
    }

    /**
     * 点赞
     */
    function praise(divObj,dynamicId) {
        $.ajax(
            {
                type: "POST",
                url: "/dynamic/praiseDynamic",
                async: false,    //异步请求
                cache: true,
                data: {
                    "dynamicId": dynamicId
                },
                success: function (data) {
                    var parise = divObj.children;
                    // 1. 更新 点赞icon 的样式
                    if(data["res"] == "add") {  //说明是点赞，修改点赞状态以及现在的点赞数量
                        parise[0].classList.add("alive");
                    } else {
                        parise[0].classList.remove("alive");
                    }
                    //2. 更新现在的点赞数量
                    parise[1].innerHTML = data["praiseNum"];
                },
                error: function (data) {
                    swal("Error", "网络错误，请联系管理员！", "error");
                }
            }
        );
    }

    function userMainPage(userId) {
        window.location.href = "/user/userMainPage?userId=" + userId;
    }
</script>
</body>
</html>
